package day02;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoAccessLog extends HttpServlet {
	private BufferedWriter writer;
	private DateFormat formatter;
	
	@Override
	public void init() throws ServletException {
		// 读取当前servlet的初始化参数
//		ServletConfig config = getServletConfig();
//		String logFile = config.getInitParameter("logFile");
//		String dateFormat = config.getInitParameter("dateFormat");
		
		// 读取全局的servlet初始化参数
		ServletContext context = getServletContext();
		String logFile = context.getInitParameter("logFile");
		String dateFormat = context.getInitParameter("dateFormat");
		
		try {
			writer = new BufferedWriter(new FileWriter(logFile, true));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		formatter = new SimpleDateFormat(dateFormat);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ServletContext context = getServletContext();
		System.out.println("context:" + context);
		System.out.println(context.getAttribute("count"));

		System.out.println(req.getRemoteAddr());
		Date date = new Date();
		System.out.println(date);
		System.out.println("有人访问了。。。");
		
		String content = req.getRemoteAddr() + "\t" + formatter.format(date);
		
		logFile(content);
	}

	private void logFile(String content) {
		synchronized (this) {
			try {
				writer.write(content);
				writer.write("\n");
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void destroy() {
		if (writer != null) {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
